import { Login } from '@/api/login.js' //接口
import { setToken, setUserName, getUserName, removeToken, removeUserName, getToken } from '@/utils/app.js'

const state = {
    //html5本地储存
    isCollapse: false || JSON.parse(sessionStorage.getItem('isCollapse')),
    // cookie本地存储
    // isCollapse: JSON.parse(Cookie.get("isCollapse")) || false,

    //存储token
    to_ken: '',
    username: getUserName() || ''
}
const getters = {
    isCollapse: state => state.isCollapse,
    // username: state => state.username
}

const mutations = {
    SET_COLLAPES(state) {
        state.isCollapse = !state.isCollapse;
        // cookie浏览器端储存
        //CooKie的异常,当cookie名单中没有isCollapse的时候,
        // 它在调用Cookit.get()方法的时候,JSON.parse()的时候会出现错误的情况
        // Cookie.set("isCollapse", JSON.stringify(state.isCollapse))
        //html5本地储存
        sessionStorage.setItem('isCollapse', JSON.stringify(state.isCollapse))
    },
    SET_TOKEN(state, value) {
        state.to_ken = value
    },
    SET_USERNAME(state, value) {
        state.username = value
    },
    // REMOVE_TOKEN() {
    //     state.to_ken = ''
    // }
}


const actions = {
    login(content, requestData) {
        return new Promise((resolve, reject) => {
            //接口
            Login(requestData).then(response => {
                let data = response.data.data;
                // console.log(response)
                content.commit('SET_TOKEN', data.token)
                content.commit('SET_USERNAME', data.username)
                setToken(data.token);
                setUserName(data.username);
                resolve(response)
                    // console.log(content.state.to_ken)
            }).catch(error => {
                reject(error)
            })
        })
    },
    exit({ commit }) {
        return new Promise((resolve, reject) => {
            removeToken();
            removeUserName();
            commit('SET_TOKEN', '')
            commit('SET_USERNAME', '')
            resolve();
        })
    }
}
export default {
    //处理命名空间问题
    namespaced: true,
    state,
    getters,
    mutations,
    actions
};